import { forEach } from '@angular/router/src/utils/collection'
import { Component, OnInit } from '@angular/core'
import { DatatableComponent } from '@swimlane/ngx-datatable/release'
import { JsonApiService } from 'app/core/api/json-api.service'
import { Router, ActivatedRoute } from '@angular/router'
import { config } from '../../shared/smartadmin.config'
import { NotificationService } from '../../shared/utils/notification.service'

declare var $: any
@Component({
  selector: 'sa-outsource-user',
  templateUrl: './outsource-user.component.html',
  styleUrls: ['./outsource-user.css']
})
export class OutsourceUserComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      useTypeL2: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择车辆用途'
          },
          remote: {
            url: config.BaseURL + 'installRoyaltyScheme/checkRoyaltyScheme.html',
            message: '该车型用途已存在',
            type: 'post',
            dataType: 'json',
            data: function (validator) {
              const formId = validator.getFieldElements('useTypeL2').attr('formId')
              return {
                useTypeL2: $('#useTypeSelect').val(),
                id: formId
              }
            }
          }
        }
      }
    }
  }

  tableData: any = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 0 //分页当前页
  pageSize: number = 10 //分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  userAdd: boolean = false
  userEdit: boolean = false
  userDeleteBatch: boolean = false
  userResetPassword: boolean = false
  installRoyalty: boolean = false
  userType: string = '' //用户类型
  workerType: string | number = '' //员工类型
  outsourcingTeamId: string = '' //实施团队
  outsourcingTeamName: string = '' //实施团队名称
  inputApi: any = 'user/teamTree.html'
  isShowRoot: boolean = false
  userTypeList: any = [] // 用户类型列表

  installRoyaltyPageSize: number = 10 // 安装提成的页的条数
  installRoyaltyCurPage: any = 1 // 当前页码
  installRoyaltytotalCount: number = 0 // 分页总条数
  installRoyaltyTableData: any = [] // 安装提成表格数据
  fromType: 'new' | 'update' | 'detail' | '' = '' // 安装提成弹框类型

  // form表单初始值
  installRoyaltyFormInit = {
    useTypeL1: '',
    useTypeL2: '',
    schemesJson: [
      {
        sensorType: null as number | null,
        numStart: null as number | null,
        numEnd: null as number | null,
        royalty: null as number | null
      }
    ],
    id: ''
  }

  installRoyaltyForm: any = {} // 安装提成表单数据
  carTypeList = carTypeListObj.carTypeList // 车辆用途枚举
  carDeatailUseList = carTypeListObj.carDeatailUseList // 表格车辆用途枚举

  sensorTypeEm = [
    {
      value: 1,
      label: '17-4（V1）'
    },
    {
      value: 2,
      label: '高精度17-4'
    }
  ]
  sensorType: any = ''

  constructor(
    private jsonApiService: JsonApiService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private notificationService: NotificationService
  ) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  //初始化钩子函数
  ngOnInit() {
    this.initBtn()
    this.load()
    this.initUserTypeList()
  }

  // 获取用户类型列表
  initUserTypeList() {
    this.jsonApiService.http('role/userTypeList.html', {}).subscribe(data => {
      if (data.success) {
        for (let index = 0; index < data.data.length; index++) {
          const element = data.data[index]
          element.text = element.userTypeName
          element.id = element.userType
        }
        this.userTypeList = data.data
      }
    })
  }
  //刷新
  refresh() {
    this.curPage = 1
    this.load()
  }
  //get权限按钮数据
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_outsource-management:outsource-user')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'outsource:addBtn' && item.parentId) {
        this.userAdd = true
      }
      if (item.sourceKey === 'outsource:editBtn' && item.parentId) {
        this.userEdit = true
      }
      if (item.sourceKey === 'outsource:deleteBatch' && item.parentId) {
        this.userDeleteBatch = true
      }
      if (item.sourceKey === 'outsource:resetPassword' && item.parentId) {
        this.userResetPassword = true
      }
      if (item.sourceKey === 'device:management:outsource:user:royalty' && item.parentId) {
        this.installRoyalty = true
      }
    }
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        name: this.searchKey,
        userType: this.userType,
        workerType: this.workerType,
        outsourcingTeamId: this.outsourcingTeamId
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('outsourcingUser/queryOutsourcingList.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      }
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //新建
  new_user() {
    this.router.navigate(['/device-management/outsource-user/user-page'], { queryParams: { type: 'new' } })
  }
  //编辑页面
  updata_user(id) {
    this.router.navigate(['/device-management/outsource-user/user-page'], {
      queryParams: { id: id, type: 'updata', nowPage: this.curPage }
    })
  }
  //表格删除用户
  del_user(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'ids=' + row.id
      this.jsonApiService.http('outsourcingUser/outsourcingUserInfoDelete.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //密码重置
  reset_password(row) {
    this.jsonApiService.confirm_message('此操作将重置密码,确认要重置?').then(() => {
      let reqdata = 'id=' + row.id + '&name=' + row.name + '&userName=' + row.userName + '&userType=' + row.userType
      this.jsonApiService.http('user/resetPassword.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }

  message(data) {
    this.notificationService.smallBox({
      content: data,
      timeout: 1000
    })
  }

  companyList: any = []
  isScroTopNum: any = 0 //当用户重新点开添加再进行点击维修点选择时才滚动到头部 其他时候不滚动
  companyTeamSelected(data) {
    $('button[type="submit"]').removeAttr('disabled')
    this.outsourcingTeamId = data.companyId || ''
    this.outsourcingTeamName = data.companyName || ''
    this.companyList = data.companyList || []
  }

  // 显示维修点选择弹窗
  selectedCar: any = [] // 选择的车辆
  userId = ''
  showMaintenance(modal, userId) {
    this.userId = userId
    this.initDeviceTree(userId)
    // 先清空再勾选
    $('#deviceList').jstree('uncheck_all')
    for (let i = 0; i < this.selectedCar.length; i++) {
      $('#deviceList')
        .jstree()
        .select_node('#' + this.selectedCar[i].id)
    }
    modal.show()
    // 当用户点击完添加第一次点开车辆树时会滚动到头部
    this.isScroTopNum++
    if (this.isScroTopNum <= 1 || this.selectedCar.length == 0) {
      let timer = setTimeout(() => {
        $('#tree_content').scrollTop(0)
        clearTimeout(timer)
        timer = null
      }, 200)
    }
  }
  // 选择维修点树的提交
  userMaintenancePermissionSubmit(modal) {
    var tree = $('#deviceList').jstree()
    var selected = tree.get_checked(true) //获取所有选中节点
    this.selectedCar = []
    let repairPointIds = ''
    var len = selected.length
    if (len < 1) {
      this.message('维修点数量不能小于1')
      return
    }
    for (var i = 0; i < len; i++) {
      if (selected[i].parents.length > 2) {
        repairPointIds += i === len - 1 ? selected[i].id : selected[i].id + ','
      }
    }
    let userId = this.userId
    let that = this
    let url = 'maintenance/addEmpByRepairPointIds.html'
    $.ajax({
      type: 'POST',
      url: config.BaseURL + url,
      dataType: 'json',
      cache: false,
      data: {
        userId,
        repairPointIds
      },
      xhrFields: {
        withCredentials: true
      },
      success: function (data: any) {
        that.closeCarTreeModal(modal)
        that.message(data.message)
        that.refresh()
      }.bind(this)
    })
    // this.selectedCar = [];
  }

  // 关闭维修点选择弹框
  closeCarTreeModal(modal) {
    $('#deviceList').jstree('destroy')
    $('#deviceList').on('changed.jstree', function (e, data) {})
    modal.hide()
  }
  // 选择维修点树的弹框提交
  selectSubmit(modal) {
    this.userMaintenancePermissionSubmit(modal)
  }

  allOpen() {
    $('#deviceList').jstree(true).open_all()
  }
  //折叠tree
  allClose() {
    $('#deviceList').jstree(true).close_all()
  }

  // 初始化车辆数据
  jsTreeData: any = [] //所有车辆数据
  selectedPointNum = 0
  initDeviceTree(userId) {
    var _that = this
    $('#deviceList').jstree({
      core: {
        data: function (obj, callback) {
          var jsonstr = '[]'
          var jsonarray = eval('(' + jsonstr + ')')
          var url = 'maintenance/getProvinceRepairPointTree.html'
          $.ajax({
            type: 'POST',
            url: config.BaseURL + url,
            dataType: 'json',
            cache: false,
            data: {
              userId
            },
            xhrFields: {
              withCredentials: true
            },
            success: function (data: any) {
              var result = data.data
              jsonarray = result
              _that.jsTreeData = result
              callback.call(this, jsonarray)
            }.bind(this)
          })
        }.bind(this),
        themes: {
          responsive: true
        },
        multiple: true,
        animation: 200,
        dblclick_toggle: true,
        expand_selected_onload: true
      },
      checkbox: {
        keep_selected_style: false,
        three_state: false, //父子级别级联选择
        cascade: 'down'
        // "tie_selection": false
      },
      plugins: ['checkbox', 'search']
    })
    $('#deviceList').on('changed.jstree', function (e, data) {
      let tree = $('#deviceList').jstree()
      let selected = tree.get_checked(true)
      let len = selected.length
      let selectedPointNum = 0
      for (var i = 0; i < len; i++) {
        if (selected[i].parents.length > 2) {
          selectedPointNum += 1
        }
      }
      _that.selectedPointNum = selectedPointNum
    })
  }

  // 总共搜索到的数据
  searchResult = 0
  // 第几个
  findIndex = 0
  // 维修点数的搜索
  list_search() {
    let that = this
    let searchkey = ($('#searchKeyList').val() + '').trim()
    if (!searchkey) {
      $('#searchCountWrap').css('display', 'none')
      return
    }
    $('#deviceList').jstree(true).search(searchkey)
    this.searchResult = $('#deviceList .jstree-search').length
    if (this.searchResult < 1) {
      $('#searchCountWrap').css('display', 'none')
      layer.msg('没有对应数据', {
        icon: 0
      })
      return
    }
    // 这里是进行搜索的地方
    $('#deviceList .jstree-search').each(function (index, obj) {
      if (index < 1) {
        //js树搜索定位到结果的第一个地方；
        $('#searchCountWrap').css('display', 'inline-block')
        that.findIndex = 0
        $('#findIndex').text(that.findIndex + 1)
        $('#searchResult').text(that.searchResult)
        // 滚动
        var container = $('#tree_content'),
          scrollTo = $(this)
        $(this).addClass('jstree-hovered')
        container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop())
        container.animate({
          scrollTop:
            scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#tree_content').height() * 0.3
        })
      }
    })
  }

  // --------------------------------- 安装提成（正式员工）列表相关  -------------------------------------//

  // 点击弹出安装提成（正式员工）弹框
  handleInstallRoyalty(modal) {
    // this.installRoyaltySearchKey = ''
    // 加载表单数据
    this.loadInstallRoyalty()
    modal.show()
  }

  // 关闭安装提成弹框
  cancelInstallRoyalty(modal) {
    modal.hide()
  }

  // 安装提成表单刷新
  installRoyaltyTableRefresh() {
    this.loadInstallRoyalty()
  }

  //分页回调
  installRoyaltyPaginate(e) {
    this.installRoyaltyCurPage = e.page + 1
    this.installRoyaltyPageSize = e.rows
    this.loadInstallRoyalty()
  }

  // 加载安装提成表数据
  loadInstallRoyalty() {
    let param = {
      pageSize: this.installRoyaltyPageSize,
      nowPage: this.installRoyaltyCurPage,
      parameters: {}
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('installRoyaltyScheme/pageInstallRoyaltyScheme.html', reqdata).subscribe(data => {
      this.installRoyaltyTableData = data.exhibitDatas.map(item => {
        item.useTypeL2Name = this.carDeatailUseList[item.useTypeL2]
        return item
      })
      this.installRoyaltytotalCount = data.recordCount
    })
  }

  // --------------------------------- 安装提成（正式员工）添加/编辑表单相关  -------------------------------------//
  // 点击添加安装提成
  installRoyaltyAdd(modal, type) {
    this.fromType = type
    $('#useTypeSelect').val('').trigger('change')
    $('#setInstallRoyaltyFrom').data('bootstrapValidator').resetForm()
    this.installRoyaltyForm = this.deepClone(this.installRoyaltyFormInit)
    modal.show()
  }

  // 点击编辑/详情安装提成
  editOrDetailInstallRoyalty(row, modal, type) {
    this.fromType = type
    const rowData: Record<string, any> = this.deepClone(row)
    rowData.schemesJson = rowData.schemes.map(item => {
      item.royalty = item.royalty / 100
      return item
    })
    this.installRoyaltyForm = rowData
    modal.show()
    setTimeout(() => {
      $('#useTypeSelect').val(this.installRoyaltyForm.useTypeL2).trigger('change')
    })
  }

  // 新增提成项
  addRoyaltyItem() {
    this.installRoyaltyForm.schemesJson.push({
      sensorType: null, //传感器类型
      numStart: null, //传感器数量开始区间
      numEnd: null, //传感器数量结束区间
      royalty: null //安装提成
    })
  }

  // 删除提成项
  removeRoyaltyItem(index: number) {
    this.installRoyaltyForm.schemesJson.splice(index, 1)
  }

  // 动态表单项赋值
  formDataChange(value: number, index: number, type: string) {
    this.installRoyaltyForm.schemesJson[index][type] = value
  }

  // 提交添加/编辑表单
  submitInstallRoyalty(modal) {
    $('#setInstallRoyaltyFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setInstallRoyaltyFrom').data('bootstrapValidator').isValid() //验证是否通过

    if (isValid) {
      const data: Record<string, any> = this.deepClone(this.installRoyaltyForm)
      data.useTypeL2 = $('#useTypeSelect').val()
      data.useTypeL1 = $('#useTypeSelect').val().slice(0, 2)

      data.schemesJson.forEach(item => {
        item.royalty = item.royalty * 100
      })
      data.schemesJson = JSON.stringify(data.schemesJson)
      this.jsonApiService.http_obj('installRoyaltyScheme/addInstallRoyaltyScheme.html', data).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadInstallRoyalty()
          this.closeInstallRoyalty(modal)
        }
      })
    }
  }

  // 关闭添加/编辑弹框
  closeInstallRoyalty(modal) {
    $('#setInstallRoyaltyFrom').data('bootstrapValidator').resetForm()
    modal.hide()
  }

  // 删除安装提成
  delInstallRoyalty(row) {
    this.jsonApiService.confirm_message('是否确定删除该车型用途的提成方案？').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('installRoyaltyScheme/delInstallRoyaltyScheme.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadInstallRoyalty()
        }
      })
    })
  }

  //深拷贝浅拷贝
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }
}
